package keeto.com.vn.classified.ui;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import keeto.com.vn.classified.config.IConfig;
import keeto.com.vn.classified.config.IConstant;
import keeto.com.vn.classified.config.SettingKey;
import keeto.com.vn.classified.core.ClassifiedListener;
import keeto.com.vn.classified.utils.FileUtils;
import keeto.com.vn.classified.utils.ImageUtilities;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ChooseImageFromLib extends Activity {
	private static final String ACTION_CHOOSE_AVATAR = "com.supersabona.im.ui.activity.ChooseImageFromLib.ChooseAvatar";
	private static final String ACTION_CHOOSE_BACKGROUND = "com.supersabona.im.ui.activity.ChooseImageFromLib.ChooseBackground";

	protected static final String TAG = "ChooseImageFromLib";
	private static String KEY_LISTENER = null;

	private String Action = "";
	private TextView tvTitle = null;
	private ImageButton btnBack = null;
	private GridView gridImage = null;
	private MyAvatarAdapter iAdapter = null;
	private LayoutInflater mLayoutInflater;
	public ArrayList<String> pathImage = null;
	private static final int ADD_FROM_SERVER = 10;
	private static final int ADD_FROM_GALLERY = 11;
	private static final int ADD_FROM_CAMERA = 12;
	private String filepath_take_image = "";

	private Uri mUri = null;
	private Bitmap mBitmap = null;

	private String path = null;
	private String mFilepath = null;
	private String iPath = null;
	private ProgressDialog mProgressDialog = null;
	private DownloadListener listener = new DownloadListener();
	private ArrayList<String> linksImageDefault = new ArrayList<String>();
	private DownloadTaskImage taskImage = null;

	public static final int DIALOG_DOWNLOAD_PROGRESS = 0;

	private ChooseImageHandler imageHandler = new ChooseImageHandler();
	private int[] avatar_default ={R.drawable.avatar_def_1}; 
	private boolean ischooseAvatar = false;

	@Override
	protected void onCreate(Bundle icicle) {
		// TODO Auto-generated method stub
		super.onCreate(icicle);
		mLayoutInflater = (LayoutInflater) this
				.getSystemService(LAYOUT_INFLATER_SERVICE);
		setContentView(R.layout.choose_image_lib_layout);
		setTitle(getString(R.string.title_choose_image));

		Intent it = getIntent();
		Action = it.getAction();
		if (Action.equals(ACTION_CHOOSE_AVATAR)) {
			path = Environment.getExternalStorageDirectory()
					+ IConfig.PATH_LIB_AVATAR;
			KEY_LISTENER = "avatar";
			ischooseAvatar = true;
		} else if (Action.equals(ACTION_CHOOSE_BACKGROUND)) {
			path = Environment.getExternalStorageDirectory()
					+ IConfig.PATH_LIB_BACKGROUND;
			KEY_LISTENER = "background";

		}

		initUIComponents();
		LoadImagefromSource(path);
	}

	public void initUIComponents() {
		tvTitle = (TextView) findViewById(R.id.common_title_text);
		tvTitle.setText(R.string.title_choose_image);
		btnBack = (ImageButton) findViewById(R.id.common_back);
		btnBack.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		gridImage = (GridView) findViewById(R.id.gridChooseImage);
		pathImage = new ArrayList<String>();
		pathImage.add("open");
		if (ischooseAvatar){
			pathImage.add("defaut_1");
			pathImage.add("defaut_2");
			pathImage.add("defaut_3");
		}
		iAdapter = new MyAvatarAdapter(ChooseImageFromLib.this, KEY_LISTENER);
		gridImage.setAdapter(iAdapter);

	}

	private void LoadImagefromSource(final String path) {
		pathImage.clear();
		pathImage.add("open");
		//		if (Action.equals(ACTION_CHOOSE_AVATAR)){
		//			for(int i =0; i<avatar_default.length;i++){
		//				pathImage.add( +avatar_default.hashCode()[i]);
		//			}
		//		}

		if (ischooseAvatar){
			pathImage.add("defaut_1");
			pathImage.add("defaut_2");
			pathImage.add("defaut_3");
		}

		File fileDir = new File(path);
		if (!fileDir.exists()) {
			fileDir.mkdir();
		}
		File[] files = fileDir.listFiles();
		if (files != null && files.length > 0){
			try {
				for (File fi : files) {
					pathImage.add(fi.getAbsolutePath());
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}

		if (iAdapter != null) {
			iAdapter.notifyDataSetChanged();
		}

	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	public class MyAvatarAdapter extends BaseAdapter {

		public Context context;
		String curren_Path = "";

		public MyAvatarAdapter(Context ctx, String key) {
			this.context = ctx;
			if (key.equals("avatar")) {
				SharedPreferences preferences = getSharedPreferences(
						SettingKey.SHARED_PREFERENCE_NAME, MODE_PRIVATE);
				curren_Path = preferences.getString(
						IConstant.PATH_SAVE_AVATAR_IN_LIBRARY, "");
			} else {
				SharedPreferences preferences = getSharedPreferences(
						SettingKey.SHARED_PREFERENCE_NAME, MODE_PRIVATE);
				curren_Path = preferences.getString(
						IConstant.PATH_SAVE_BACKGROUND_LIBRARY, "");
			}
		}

		private ArrayList<ViewHolder> liHolders = new ArrayList<ChooseImageFromLib.MyAvatarAdapter.ViewHolder>();

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return pathImage.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return pathImage.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			// TODO Auto-generated method stub
			final ViewHolder holder;
			if (convertView == null) {
				convertView = mLayoutInflater.inflate(
						R.layout.item_grid_choose_image, null);
				holder = new ViewHolder();
				holder.rlItem = (RelativeLayout) convertView
						.findViewById(R.id.rl_item_grid);
				holder.img_avatar = (ImageView) convertView
						.findViewById(R.id.img_item_grid);
				holder.cb_choose = (CheckBox) convertView
						.findViewById(R.id.cb_choose_image);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.cb_choose.setVisibility(View.INVISIBLE);

			if (position == 0) {
				holder.img_avatar
				.setImageResource(R.drawable.add_image_selector);
//			} else if (position < 4 && ischooseAvatar) {
//				holder.img_avatar
//				.setImageResource(avatar_default[position]);
//			}else{
//
//				holder.img_avatar
//				.setImageURI(Uri.parse(pathImage.get(position)));
			}

			String link = pathImage.get(position);
			if (!TextUtils.isEmpty(curren_Path)
					&& Uri.parse(pathImage.get(position)).toString().equals(curren_Path)) {
				holder.cb_choose.setVisibility(View.VISIBLE);

			}

			liHolders.add(holder);

			holder.rlItem.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (position == 0) {
						dialogloadimage();
					} else {

						if (holder.cb_choose.getVisibility() == View.INVISIBLE) {
							for (ViewHolder vh : liHolders) {
								setVisibility(vh, View.INVISIBLE);
							}
							setVisibility(holder, View.VISIBLE);
						} else {
							setVisibility(holder, View.INVISIBLE);
						}
						mFilepath = pathImage.get(position).toString();

						Intent intent = new Intent();
						intent.putExtra("filepath", mFilepath);
						setResult(RESULT_OK, intent);
						finish();
					}
				}
			});

			return convertView;
		}

		private void setVisibility(ViewHolder holder, int visible) {
			holder.cb_choose.setVisibility(visible);
		}

		public void dialogloadimage() {
			String[] data = new String[] {
					getString(R.string.download_image_from_server),
					getString(R.string.avartar_gallery),
					getString(R.string.avartar_portal_camera) };
			new AlertDialog.Builder(ChooseImageFromLib.this)
			.setTitle(R.string.add_more_image)
			.setItems(data, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					switch (which) {
					case 0: // download image
						choosefromServer();
						break;
					case 1: // choose image
						choosefromGallery();
						break;
					case 2: // take picutre
						choosefromCamera();
						break;
					}
				}
			}).show();

		}

		class ViewHolder {
			private RelativeLayout rlItem;
			private ImageView img_avatar;
			private CheckBox cb_choose;
		}
	}

	public static void chooseAvatarfromLib(Activity context, int requestCode) {
		Intent intent = new Intent(context, ChooseImageFromLib.class);
		intent.setAction(ACTION_CHOOSE_AVATAR);
		context.startActivityForResult(intent, requestCode);
	}

	public static void chooseBackgroundfromLib(Activity context, int requestCode) {
		Intent intent = new Intent(context, ChooseImageFromLib.class);
		intent.setAction(ACTION_CHOOSE_BACKGROUND);
		context.startActivityForResult(intent, requestCode);
	}

	public void choosefromServer() {
		mProgressDialog = new ProgressDialog(ChooseImageFromLib.this);
		mProgressDialog.setMessage("Please wait....");
		mProgressDialog.setCancelable(true);
		mProgressDialog.show();

//		IMCore.getInstance(getApplicationContext()).taskDownloadImage(
//				KEY_LISTENER, listener);

	}

	public void choosefromGallery() {
		Intent getImageFromGalleryIntent = new Intent(Intent.ACTION_PICK,
				MediaStore.Images.Media.INTERNAL_CONTENT_URI);
		startActivityForResult(getImageFromGalleryIntent, ADD_FROM_GALLERY);
	}

	public void choosefromCamera() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		filepath_take_image = path + "pic_"
				+ String.valueOf(System.currentTimeMillis()) + ".jpg";
		mUri = Uri.fromFile(new File(filepath_take_image));
		intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mUri);

		try {
			intent.putExtra("return-data", true);
			startActivityForResult(intent, ADD_FROM_CAMERA);
		} catch (ActivityNotFoundException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_DOWNLOAD_PROGRESS:
			mProgressDialog = new ProgressDialog(this);
			mProgressDialog.setMessage("Tải ảnh từ server...");
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgressDialog.setCancelable(false);
			mProgressDialog.show();
			return mProgressDialog;
		default:
			return null;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode != RESULT_OK) {
			return;
		}

		switch (requestCode) {
		case ADD_FROM_SERVER:
			LoadImagefromSource(path);

			break;
		case ADD_FROM_GALLERY:
			Log.d(TAG, "PICK_FROM_CALLERY");
			Uri selectedImage = data.getData();
			String[] filePathColumn = { MediaColumns.DATA };

			Cursor cursor = getContentResolver().query(selectedImage,
					filePathColumn, null, null, null);
			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			iPath = cursor.getString(columnIndex);
			cursor.close();
			if (!TextUtils.isEmpty(iPath)) {
				mBitmap = ImageUtilities.getBitmapThumbnailFromFile(iPath,
						MainApplication.getScreenWidth(), MainApplication.getScreenHeight());

				ImageUtilities.saveToPath(
						mBitmap,
						path + "pic_"
								+ String.valueOf(System.currentTimeMillis())
								+ ".jpg");
			}
			LoadImagefromSource(path);
			break;

		case ADD_FROM_CAMERA:

			LoadImagefromSource(path);

			break;
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	class DownloadListener extends ClassifiedListener {

//		@Override
//		public void finishDownloadLinkImage(final int returnCode,
//				final ArrayList<String> links) {
//			// TODO Auto-generated method stub
//			super.finishDownloadLinkImage(returnCode, links);
//			runOnUiThread(new Runnable() {
//
//				@Override
//				public void run() {
//					if (mProgressDialog != null)
//						mProgressDialog.dismiss();
//					if (links != null) {
//
//						for (int i = 0; i < links.size(); i++) {
//							linksImageDefault.add(links.get(i));
//							// Log.e(TAG, "LINk  " + links.get(i));
//						}
//						Log.i("DownloadListener", "DownloadListener:"
//								+ linksImageDefault.size());
//						imageHandler.downloadavatar();
//					}
//				}
//			});
//		}
	}

	class ChooseImageHandler extends Handler {
		public static final int WHAT_DOWNLOAD_AVATAR = 1;
		public static final int WHAT_DOWNLOAD_BACKGROUND = 2;

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);

			switch (msg.what) {
			case WHAT_DOWNLOAD_AVATAR:
				taskImage = new DownloadTaskImage();
				taskImage.execute();
				LoadImagefromSource(path);
				break;
			case WHAT_DOWNLOAD_BACKGROUND:
				taskImage = new DownloadTaskImage();
				taskImage.execute();
				LoadImagefromSource(path);
				break;
			}
		}

		public void downloadavatar() {
			Message message = new Message();
			message.what = WHAT_DOWNLOAD_AVATAR;
			this.sendMessage(message);
		}

		public void downloadbackground() {
			Message message = new Message();
			message.what = WHAT_DOWNLOAD_BACKGROUND;
			this.sendMessage(message);

		}
	}

	class DownloadTaskImage extends AsyncTask<String, Integer, Integer> {

		// Max size of download buffer.
		private static final int MAX_BUFFER_SIZE = 1024;

		private static final int NO_STORAGE = -1;
		private static final int DOWNLOADING = 0;
		private static final int COMPLETE = 2;
		private static final int ERROR = 4;
		private String currentUrl = "";

		@Override
		protected Integer doInBackground(String... params) {
			int status = DOWNLOADING;

			FileOutputStream fos = null;
			InputStream stream = null;
			OutputStream output = null;
			int contentLength = linksImageDefault.size();

			for (int i = 0; i < contentLength; i++) {
				currentUrl = IConfig.IA_NEW_URL_DEFAULT_IMAGE
						+ linksImageDefault.get(i);

				if (FileUtils.hasStorage(false, "")) {
					try {
						URL downloadUrl = new URL(currentUrl);
						int size = -1;
						// Open connection to URL.
						URLConnection connection = downloadUrl.openConnection();
						// Connect to server.
						connection.connect();

						if (size == -1) {
							size = contentLength;
						}

						String reverseString = new StringBuffer(currentUrl)
						.reverse().toString();
						int separatorIndex = reverseString.indexOf("/");
						int start = currentUrl.length() - separatorIndex;
						String fileName = currentUrl.substring(start,
								currentUrl.length());

						File file = new File(path, fileName);
						if (file.exists()) {
							file.delete();
						}

						output = new FileOutputStream(file);
						URL url = new URL(currentUrl);
						URLConnection conexion = url.openConnection();
						conexion.connect();
						stream = new BufferedInputStream(url.openStream());

						int latestProgress = 0;
						int count = 0;
						byte data[] = new byte[MAX_BUFFER_SIZE];
						int currentProgress = 0;
						while ((count = stream.read(data)) != -1) {
							output.write(data, 0, count);
						}
						currentProgress = (int) (((i + 1) * 100) / contentLength);
						if (currentProgress - latestProgress > 0) {
							latestProgress = currentProgress;
							publishProgress(currentProgress);
						}

					} catch (Exception e) {
						status = ERROR;
					} finally {
						// notificationManager.cancelAll();
						// Close file.
						if (fos != null) {
							try {
								output.flush();
								output.close();
							} catch (Exception e) {
							}
						}

						// Close connection to server.
						if (stream != null) {
							try {
								stream.close();
							} catch (Exception e) {
							}
						}
					}

				} else {
					return NO_STORAGE;
				}
			}
			if (status == DOWNLOADING) {
				status = COMPLETE;
			}
			return status;
		}

		@Override
		protected void onPostExecute(Integer result) {
			dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
			if (mProgressDialog != null)
				mProgressDialog.dismiss();
			if (result == COMPLETE) {
				if (mProgressDialog != null)
					mProgressDialog.dismiss();

			} else if (result == NO_STORAGE) {
				Toast.makeText(ChooseImageFromLib.this,
						getString(R.string.msg_update_client_no_outer_storage),
						Toast.LENGTH_SHORT).show();
				if (mProgressDialog != null)
					mProgressDialog.dismiss();

			} else {
				Toast.makeText(ChooseImageFromLib.this,
						getString(R.string.msg_update_client_download_failed),
						Toast.LENGTH_SHORT).show();
				if (mProgressDialog != null)
					mProgressDialog.dismiss();
			}

			LoadImagefromSource(path);
			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			showDialog(DIALOG_DOWNLOAD_PROGRESS);
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			// super.onProgressUpdate(values);
			mProgressDialog.setProgress(values[0]);
		}

	}

}
